
import React, { Component } from 'react';
import {
	StyleSheet, Text, FlatList, Animated, View, Image, Alert, TouchableOpacity
} from "react-native";
import { NavigationEvents, ScrollView } from 'react-navigation';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import ToastUtil from '../../../utils/toast';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import { STORAGE_CONSTANT } from '../../../config/storage';
import StorageHelper from '../../../utils/storageHelper';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { ProgressModal } from '../../../components/common/ProgressModal';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ResourceOfferCard } from './resourceOfferCard';
import { ResourceBaseInfoCard } from './resourceBaseInfoCard';
import ModalPicsComponent from '../../customer-management/enterprise/details/_components/ModalPicsComponent';

const scale = GLOBAL.SCALE;
const modalPicDelCfg = {
	visible: false,
	urls: [],
	picPress: () => { },
}
export class ApplyInfo extends Component {
	constructor(props) {
		super(props);
		this.state = {
			modalVisible: false,
			remarkModalVisible: false,
			status: 'loading',
			resDetail: {},
			itemData: {},
			statusLit: 'data',
			lightBoxData: {
				modalVisible: false,
				onClosePress: this._closeLightBox,
				title: '审批流',
				rowDataList: [],
				status: 'data',
				refreshIcon: false,
			},
			approveList: [],
			activeList: [],
			previewModalVisible: false
		}
		let { bidPackageId, periodNum, applyId } = this.props;
		this.pageParams = {
			bidPackageId,
			periodNum,
			applyId
		}
	}

	async componentWillMount() {
		this.userInfo = await this._getUserInfo();
		await this.initPage();
	}

	_getUserInfo = async () => {
		//获取用户信息
		let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		if (userInfo) {
			userInfo = JSON.parse(userInfo);
		}
		return userInfo || {};
	}

	//初始化数据
	initPage = async () => {
		this.setState({
			status: 'loading'
		})
		let res = await HTTP.POST(API_GENERATE(API.BIZ_APPLY_DETAIL), this.pageParams);
		if (res) {
			res = this.getRequireParams(res);
			const { packageApplyGoodsTOS, bizModel, bizModelName } = res || {};
			packageApplyGoodsTOS && packageApplyGoodsTOS.length && packageApplyGoodsTOS.map((item, index) => {
				item.bizModel = bizModel;
				item.bizModelName = bizModelName;
			})
			this.setState({
				res: res,
				resDetail: res.bidBargainApplyDetail,
				status: 'data'
			})
		} else {
			this.setState({
				status: 'error'
			})
		}
	}
	// 返回值数据补充
	getRequireParams = (res) => {
		let { packageApplyGoodsTOS } = res.bidBargainApplyDetail || {};
		if (res.bidBargainApplyDetail && packageApplyGoodsTOS && packageApplyGoodsTOS.length > 0) {
			packageApplyGoodsTOS.forEach(item => {
				item.showItem = false;
				item.boxHeight = new Animated.Value(item.resourceApplyList && item.resourceApplyList.length >= 2 ? 224 * scale : 112 * scale);
				item.openHeight = 0;
				if (item.resourceApplyList && item.resourceApplyList.length > 0) {
					item.openHeight = 112 * item.resourceApplyList.length
				} else {
					item.resourceApplyList = []
				}
			})
		}
		return res
	}

	// 查看审批流
	_getCheckApprove = async () => {
		let { applyId } = this.props
		let { processInstanceId, corpId } = this.state.resDetail || {};
		//查询审批节点AUDIT_QUERY_COMPANY
		let params = {
			bizId: applyId,
			bizObjType: 'BID_BARGAIN',
			processInstanceId,
			corpId,
		}
		let responseData = await HTTP.GET(API_GENERATE(API.APPROVAL_NODE), params);
		console.log('responseData', responseData)
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = true;
		lightBoxData.title = '审批流';
		lightBoxData.rowDataList = responseData;
		this.setState({
			lightBoxData,
			status: 'data'
		})
	}

	_closeLightBox = () => {
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = false;
		this.setState({ lightBoxData });
	}

	async getImgView(qualificationAddress) {
		if (qualificationAddress.length === 1) {
			this.setState({
				statusLit: 'loading'
			}, () => {
				qualificationAddress.map(async (fileId) => {
					await this.loadedImgs(fileId);
				})
			})
		}
		else {
			this.props.navigation.navigate('Attachment', { qualificationAddress })
		}
	}
	async loadedImgs(fileId) {
		const response = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId });
		if (response && response.image && response.image.length) {
			modalPicDelCfg.visible = true;
			modalPicDelCfg.urls.push({
				url: response.image,
				width: Dimensions.get('window').width
			});
			modalPicDelCfg.picPress = () => {
				modalPicDelCfg.visible = false;
				modalPicDelCfg.urls = [];
				this.setState({
					previewModalVisible: false,
				});
			}
		}
		this.setState({
			statusLit: 'data',
			previewModalVisible: true
		});
	}
	_approvalListItim = (item) => {
		let { resDetail } = this.state;
		let { packageApplyGoodsTOS, salesType } = resDetail || {};
		return (
			<ResourceOfferCard
				showStatus={false}
				itemForDetail={true}
				salesType={salesType}
				listData={packageApplyGoodsTOS}
				itemData={item}
				getImgView={() => this.getImgView(item.item.fileIdArry)}
				resetListData={(resetListData) => {
					packageApplyGoodsTOS = resetListData;
					this.setState({ resDetail })
				}} />
		)
	}


	render() {
		let { res, resDetail, status, showRejectModal, remarkModalVisible, curApplyRemark, lightBoxData, statusLit } = this.state;
		let { packageApplyGoodsTOS, salesType, corpId } = resDetail || {};
		let { resourceBidStatTO } = res || {}
		let { navigateTo } = this.props
		return (
			<ScrollView style={styles.container}>
				<NavigationEvents onWillFocus={async () => {
					await this.initPage();
				}} />
				{
					status == 'data' ?
						<View style={styles.body}>
							<ResourceBaseInfoCard
								checkApproveList={() => this._getCheckApprove()}
								showStatus={true}
								data={resDetail}
								copyPress={() => { navigationSeevice.navigate('OfferCreatePage', { salesType, bidPackageApplyId: resDetail.bidPackageApplyId, corpId, isCopy: true }); }} />
							{
								packageApplyGoodsTOS && packageApplyGoodsTOS.length ?
									packageApplyGoodsTOS.map((item, index) => {
										return (
											<View key={index}>
												{this._approvalListItim({ item, index })}
											</View>
										)
									}) : null
							}
							{resourceBidStatTO && resourceBidStatTO.bidStatisticsTO ?
								<View style={{ marginTop: 25 * scale }}>
									<View style={styles.offerData}>
										<Text style={styles.offerText}>上架时间：{resourceBidStatTO.bidStatisticsTO.upTime || '-'}</Text>
									</View>
									<View style={styles.offerData}>
										<Text style={styles.offerText}>下架时间：{resourceBidStatTO.bidStatisticsTO.removeTime || '-'}{resourceBidStatTO.bidStatisticsTO.diffTime ? '（持续时间：' + resourceBidStatTO.bidStatisticsTO.diffTime + '）' : null}</Text>
									</View>
									<View style={styles.offerData}>
										<Text style={styles.offerText}>是否转成交：{resourceBidStatTO.bidStatisticsTO.isMustTran === 'Y' ? '是' : '否'}</Text>
									</View>
									<TouchableOpacity style={styles.offerData} onPress={() => {
										navigateTo && navigateTo(resDetail.bidPackageApplyId, this.pageParams.periodNum)
									}}>
										<Text style={styles.offerText}>资源包编号：
											<Text style={{ color: style.color.themeColor }}>
												{resourceBidStatTO.bidStatisticsTO.bidPackageId} >
											</Text>
										</Text>
									</TouchableOpacity>
								</View> : null
							}
						</View> : null
				}
				{
					status != 'data' ? <View style={{ marginTop: '42%' }}><PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.initPage} /></View> : null
				}
				{
					statusLit != 'data' ? <View style={{ position: 'absolute', height: '100%', width: '100%' }}><PageStatusIndex status={'loading'} /></View> : null
				}
				{/* 审批流 */}
				<ProgressModal {...lightBoxData} />
				<ModalPicsComponent {...modalPicDelCfg} />
			</ScrollView>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	body: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	itemBorder: {
		height: 1 * scale,
		backgroundColor: '#E3E7F0',
		marginBottom: 15 * scale,
	},
	arrowIcon: {
		position: 'absolute',
		right: 0,
		top: 2 * scale,
		right: 32 * scale,
	},
	textRow: {
		marginBottom: 20 * scale
	},
	textRowText: {
		paddingLeft: 15 * scale
	},
	statusSelect: {
		backgroundColor: style.color.gray,
		opacity: 0.7,
		marginTop: 20 * scale,
		marginLeft: 20 * scale,
		padding: 6 * scale,
		width: 94 * scale,
		borderRadius: 20 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	statusSelectText: {
		fontSize: 13 * scale,
		marginRight: 4 * scale
	},
	statusSelectIcon: {
		width: 10 * scale,
		height: 10 * scale
	},
	baseInfoCard: {
		padding: 12 * scale
	},
	baseInfoCardTitle: {
		marginTop: 10 * scale,
		marginBottom: 12 * scale,
		fontSize: 14 * scale,
		fontWeight: 'bold'
	},
	consent: {
		paddingRight: 20 * scale,
		paddingLeft: 20 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		fontSize: 12 * scale,
		opacity: 1,
		color: '#ffffff',
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 15 * scale,
		backgroundColor: style.color.themeColor,
		overflow: 'hidden'
	},
	itemdown: {
		fontSize: 12 * scale,
		color: style.color.themeColor,
		paddingRight: 20 * scale,
		paddingLeft: 20 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 15 * scale,
		marginRight: 20 * scale,
		marginLeft: 10 * scale,
	},
	applyRemarkStyle: {
		fontSize: 13 * scale,
		color: style.color.themeColor,
		paddingLeft: 14 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale
	},
	orangeBtn: {
		paddingRight: 14 * scale,
		paddingLeft: 14 * scale,
		paddingTop: 6 * scale,
		paddingBottom: 6 * scale,
		fontSize: 12 * scale,
		opacity: 1,
		color: '#ffffff',
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: '#FA6400',
		borderRadius: 15 * scale,
		backgroundColor: '#FA6400',
		overflow: 'hidden'
	},
	ClinchRecord: {
		fontSize: 14 * scale,
		color: style.color.themeColor,
		fontWeight: 'bold',
		width: '100%',
		textAlign: 'right',
		paddingRight: 16 * scale,
		marginBottom: 10 * scale
	},
	offerData: {
		marginLeft: 16 * scale,
		marginBottom: 8 * scale,
		flexDirection: 'row',
		alignItems: 'center'
	},
	offerText: {
		fontSize: 12 * scale
	}
})